
const fs = require('fs-extra');
const path = require('path');
const axios = require('axios')

const { loading, stopLoading, print, printSuccess, printWarning, printError } = require('../utils/message-box');

const envConfig = {
    dev: 'http://cgm-ce-dev.sisensing.com',
    test: 'http://cgm-ce-test.sisensing.com',
    pre: 'https://cgm-ce-pre.sisensing.com',
    prod: 'https://cgm-ce.sisensing.com',
};

// 将内容写入指定文件
const writeDirectoryFile = async (targetDirectory, fileName, content) => {
    try {
        loading('Init Directory...');
        await fs.ensureDir(targetDirectory);
        stopLoading();
        loading('Init File...');
        const filePath = path.join(targetDirectory, fileName);
        print(` ${fileName}`);
        content = typeof content === 'string' ? content : JSON.stringify(content, null, 4);
        await fs.outputFile(filePath, content);
        printSuccess(`${filePath}`);
        stopLoading();
    } catch (err) {
        printError(`${filePath} 更新失败: \n${err}`);
        stopLoading();
    }
};

// 获取语言包内容
const getFileContent = async (proCode, options) => {
    const { env = 'dev', lang = 'en_US', http, all } = options || {};
    let baseURL = (http || envConfig[env]);
    baseURL = baseURL[baseURL.length - 1] === '/' ? baseURL.slice(0, baseURL.length - 1) : baseURL;
    try {
        const res = await axios.get(`${baseURL}/system/admin/app/project/languages?code=${proCode}`);
        const languageList = ((res || {}).data || {}).data || [];
        if (!languageList.length) {
            printError(`更新语言包失败，请请检查 ${proCode} 项目是否存在；并且已在crowdin配置了相关语言`);
            return;
        }
        print(`查询的的语言列表：${languageList.map(({ code }) => code).join(' | ')}`);
        if (all) {
            printWarning('准备下载所有语言包...');
            const getFileContent = (list) => new Promise((resolve) => {
                axios.get(list.translateUrl).then(res => {
                    resolve({ ...list, data: res.data || {} });
                }).catch(() => resolve());
            });
            const contents = await Promise.all(languageList.map(d => getFileContent(d)));
            return contents;
        }
        printWarning(`默认下载：${lang}`);
        const langObj = languageList.find(({ code }) => code === lang);
        if (!langObj) {
            printError(`${proCode}项目不存在${lang}语言包`);
            return;
        }
        if (!langObj.translateUrl) {
            printError(`${proCode}项目的${lang}语言包下载地址为空`);
            return;
        }
        const content = await axios.get(langObj.translateUrl);
        return [{ ...langObj, data: content.data }];
    } catch (error) {
        printError(`获取语言包失败: ${error}`);
    }
};

module.exports = async (proCode, options) => {
    const { path = 'src/locale', all, name = 'default', suffix = '.json' } = options || {};
    const contents = await getFileContent(proCode, options);
    if (!contents || !contents.length) return;
    if (!all) {
        writeDirectoryFile(path, `${name}${suffix}`, contents[0].data);
        return;
    }
    contents.forEach(({ code, transName, translateUrl, cdnLatestTime, data }) => {
        const messages = JSON.stringify(data, null, 4);
        const content = suffix === '.js' ? `
// ${transName} - ${code} - ${translateUrl}
// 翻译cdn同步时间: ${new Date(cdnLatestTime)}
const messages = ${messages};

export default messages;` : messages;
        writeDirectoryFile(path, `${code}${suffix}`, content);
    });
};